<template>
  <div class="app-container">
    <el-form ref="form" label-width="160px">
      <el-form-item label="选择要分区的喷灌机：">
        <el-select v-model="serialno" style="width:250px;" clearable filterable placeholder="请选择要分区的喷灌机" @change="setCurrentDevice">
          <el-option
            v-for="(item,index) in sprinklers"
            :key="index"
            :label="`${item.name} - ${item.serialno}`"
            :value="item.serialno"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <el-empty v-if="!serialno" description="暂未选择任何喷灌机" />
    <div v-else>
      <!-- <div class="h12" />
      <el-divider content-position="left"><b>喷灌机属性</b></el-divider>
      <el-row>
        <el-col :span="8" class="attr"><b>设备名称：</b>{{ currentDevice.dname }}</el-col>
        <el-col :span="8" class="attr"><b>喷头数量：</b>{{ currentDevice.portArrays.length }}</el-col>
        <el-col :span="8" class="attr"><b>整机长度：</b>{{ getDeviceRadius(currentDevice.extension) }}米</el-col>
      </el-row>
      <div class="h20" /> -->
      <div class="h20" />
      <el-divider content-position="left">
        <b>分区设置</b>
        <el-button
          v-if="serialno"
          style="margin-left:8px;"
          size="mini"
          type="primary"
          icon="el-icon-plus"
          circle
          @click="addCell(0)"
        />
      </el-divider>
      <el-table
        :data="cellsFormater"
        border
        row-key="id"
        style="width: 100%;margin-bottom:20px;"
      >
        <el-table-column
          prop="name"
          label="分区"
          align="left"
          width="128"
        />
        <el-table-column
          prop="name"
          label="编号"
          align="center"
          width="80"
        >
          <template v-slot="scope">
            <span v-if="scope.row.children">{{ scope.row.id }}</span>
            <span v-else>{{ scope.row.idx }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="喷头范围"
          align="center"
        >
          <template v-slot="scope">
            <div v-if="scope.row.pid" style="display:flex;align-items:center;">
              <el-input v-model="scope.row.spstart" placeholder="起始喷头" size="small" />
              <span style="padding:0 8px;"> ~ </span>
              <el-input v-model="scope.row.spend" placeholder="终止喷头" size="small" />
            </div>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <!-- <el-table-column
          prop="address"
          label="距离范围（米）"
          align="center"
        >
          <template v-slot="scope">
            <div v-if="scope.row.pid" style="display:flex;align-items:center;">
              <el-input v-model="scope.row.disstart" placeholder="起始距离" size="small" />
              <span style="padding:0 8px;"> ~ </span>
              <el-input v-model="scope.row.disend" placeholder="终止距离" size="small" />
            </div>
            <span v-else>--</span>
          </template>
        </el-table-column> -->
        <el-table-column
          prop="address"
          label="角度范围（度）"
          align="center"
        >
          <template v-slot="scope">
            <div v-if="scope.row.children" style="display:flex;align-items:center;">
              <el-input v-model="scope.row.argstart" placeholder="起始角度" size="small" @change="changeRow(scope.row,'argstart')" />
              <span style="padding:0 8px;"> ~ </span>
              <el-input v-model="scope.row.argend" placeholder="终止角度" size="small" @change="changeRow(scope.row,'argend')" />
            </div>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="颜色"
          align="center"
          width="80"
        >
          <template v-slot="scope">
            <el-color-picker v-model="scope.row.color" :disabled="Boolean(scope.row.children)" show-alpha />
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="操作"
          align="center"
          width="100"
        >
          <template slot-scope="scope">
            <el-button :disabled="scope.row.pid > 0" size="mini" type="primary" icon="el-icon-plus" circle @click="addCell(scope.row)" />
            <el-button size="mini" type="danger" icon="el-icon-delete" circle @click="removeCell(scope.row,scope.$index)" />
          </template>
        </el-table-column>
      </el-table>
      <el-button
        type="primary"
        :loading="loading.show"
        @click="submit"
      >
        {{ loading.text }}
      </el-button>
    </div>
  </div>
</template>

<script>
import { formatCells } from '@/utils'
import { dclassCodeMap } from '@/utils/constant'
import { mapGetters } from 'vuex'
import { getCells, save } from '@/api/cell'
export default {
  props: {
    partitionSerialno: {
      type: Object,
      default: () => {}
    }
  },

  data() {
    return {
      serialno: '',
      currentDevice: {},
      cellsFormater: [],
      loading: {
        text: '提交',
        show: false
      }
    }
  },
  computed: {
    ...mapGetters(['devices', 'cells']),
    sprinklers() {
      return this.devices.filter((val) => {
        return +val.product_type === dclassCodeMap.pg
      })
    }
  },
  methods: {
    async setCurrentDevice(serialno) {
      if (serialno) {
        const { data } = await getCells({ serialno })
        this.cellsFormater = formatCells(data)
      }
    },
    getDeviceRadius(extension) {
      return JSON.parse(extension.replace(/'/g, '"')).arm
    },
    addCell(pid) {
      if (pid === 0) {
        const id = this.cellsFormater.length + 1
        const item = {
          id: id,
          name: '管理区' + id,
          children: [
            {
              idx: 1,
              id: id + '' + 1,
              pid: id,
              name: '小分区1'
            }
          ]
        }
        this.cellsFormater.push(item)
      } else {
        const idx = pid.children.length + 1
        pid.children.push({
          idx: idx,
          id: pid.id + '' + idx,
          pid: pid.id,
          name: '小分区' + idx
        })
      }
    },
    removeCell(row, index) {
      if (row.children) {
        this.cellsFormater.splice(index, 1)
      } else {
        const parent = this.cellsFormater.filter(function(val) { return val.id === row.pid })[0]
        const cindex = parent.children.findIndex(value => {
          return value.idx === row.idx
        })
        parent.children.splice(cindex, 1)
      }
    },
    changeRow(row, field) {
      console.log(row)
      row.children.map(val => { val[field] = row[field] })
    },
    async submit() {
      this.loading = {
        text: '处理中',
        show: true
      }
      const cells = this.formatSubmitData(this.cellsFormater)
      const { msg, data } = await save(this.serialno, cells).catch(() => {
        this.loading = {
          text: '提交',
          show: false
        }
      })
      this.$store.commit('device/SET_CELLS', data)
      this.$message.success(msg)
      this.loading = {
        text: '提交',
        show: false
      }
      setTimeout(() => {
        this.$emit('switchProject')
      }, 1000)
    },
    formatSubmitData(cells) {
      const cellsClone = JSON.parse(JSON.stringify(cells))
      let result = []
      cellsClone.forEach((item) => {
        item.children.map(val => {
          val.id = val.pid
          val.name = val.id + '-' + val.idx
          val.argstart = item.argstart
          val.argend = item.argend
          Object.assign(val, { serialno: this.serialno })
          delete val.pid
          delete val.radius
        })
        result = result.concat(item.children)
      })
      return result
    }
  }
}
</script>

<style lang="scss" scoped>
.attr{
  font-size:14px;
  color:#666;
}
</style>
